package com.iris.live.services.services.impl;

import com.google.common.base.Strings;
import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.common.reconsitution.FinanceConstant;
import com.iris.live.services.data.models.销售财务表Model;
import com.iris.live.services.data.models.销售财务账目表Model;
import com.iris.live.services.data.repositories.FinanceOrderRedPushRepository;
import com.iris.live.services.data.repositories.销售财务表Repository;
import com.iris.live.services.data.repositories.销售财务账目表Repository;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.report.ExcelReportContext;
import com.iris.live.services.report.IExcelReportService;
import com.iris.live.services.report.sources.ExportFinanceRedPushSource;
import com.iris.live.services.services.FinanceOrderRedPushService;
import com.iris.live.services.services.FinanceReceivablesService;
import com.iris.live.services.services.FinanceWriteOffService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/12/15.
 */
@Service
public class FinanceOrderRedPushServiceImpl implements FinanceOrderRedPushService {
    private static final Logger logger = LoggerFactory.getLogger(FinanceOrderRedPushServiceImpl.class);

    @Resource
    private FinanceOrderRedPushRepository financeOrderRedPushRepository;

    @Resource
    private 销售财务表Repository 销售财务表repository;

    @Resource
    private 销售财务账目表Repository 销售财务账目表repository;

    @Autowired
    private IExcelReportService excelReportService;

    @Resource(name = "ExportFinanceRedPushSource")
    private ExportFinanceRedPushSource exportRedPushSource;

    @Resource
    private FinanceReceivablesService financeReceivablesService;

    public FinanceOrderRedPushServiceImpl() {
    }

    @Override
    public PageData getFinanceOrderRedPush(String permit,FinanceWriteOffService.FinanceWriteOffRequest request) {
        return financeOrderRedPushRepository.getFinanceOrderRedPush(permit,request);
    }

    @Override
    public ResultData saveFinanceOrderRedPush(FinanceOrderRedPushRequest request) throws Exception {
        ResultData result = new ResultData("false",null,null);
        //判空处理
        if (Strings.isNullOrEmpty(request.billDate)){
            result.setResult("false");
            result.setMessage("请输入红冲日期");
            return result;
        }

        Timestamp time = new Timestamp(System.currentTimeMillis());  // 当前时间
        Timestamp ts = DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new java.util.Date());
        销售财务表Model financialModel = null;

        销售财务账目表Model FinModel = 销售财务账目表repository.findOne(request.AccountId);
        if(FinModel == null){
            logger.warn("找不到账目信息。 账目ID={}", request.AccountId);
            return new ResultData("false","找不到账目信息。",null);
        }

        // 红冲的单子不可以红冲
        if (FinModel.get账目类型().contains("红冲")) {
            result.setMessage("红冲单据不可红冲！");
            result.setResult("false");
            return result;
        }
        // 已经红冲的单子，不可以再次红冲
        if (null != FinModel.get是否红冲() && "1".equals(FinModel.get是否红冲())) {
            result.setMessage("单据已经被红冲过！");
            result.setResult("false");
            return result;
        }

        BigDecimal money = FinModel.get账目金额();
        financialModel = 销售财务表repository.findByOrderNumber(request.initNum);
        销售财务账目表Model model = new 销售财务账目表Model();
        if (financialModel != null) {  // 已经有财务主数据,更新金额
            if (FinanceConstant.SHOUKUAN.equals(FinModel.get账目类型())){
                financialModel.set红冲收款金额(financialModel.get红冲收款金额().subtract(money));
                model.set账目类型("红冲收款");
                model.set账目单号(financeReceivablesService.generateOperationNumber(FinanceConstant.HS));
            }else if (FinanceConstant.TUIKUAN.equals(FinModel.get账目类型())){
                financialModel.set红冲退款金额(financialModel.get红冲退款金额().subtract(money));
                model.set账目类型("红冲退款");
                model.set账目单号(financeReceivablesService.generateOperationNumber(FinanceConstant.HF));
            }else if (FinanceConstant.GUAZHANG.equals(FinModel.get账目类型())){
                // 如果挂账对应的核销没有红冲的话，不能红冲该条挂账
                List<销售财务账目表Model> writeOfModels = 销售财务账目表repository.getWriteOfRecordOfBill(FinModel.get账目编号());
                if (null != writeOfModels && !writeOfModels.isEmpty()) {
                    result.setMessage("请先红冲挂账下的核销记录！");
                    result.setResult("false");
                    return result;
                }

                financialModel.set红冲挂账金额(financialModel.get红冲挂账金额().subtract(money));
                model.set账目类型("红冲挂账");
                model.set账目单号(financeReceivablesService.generateOperationNumber(FinanceConstant.HG));
            }else if (FinanceConstant.HEXIAO.equals(FinModel.get账目类型())){
                financialModel.set红冲核销金额(financialModel.get红冲核销金额().subtract(money));
                model.set账目类型("红冲核销");
                model.set账目单号(financeReceivablesService.generateOperationNumber(FinanceConstant.HH));
            }
            financialModel.set修改时间(time);
            financialModel.set修改用户(request.user);

            销售财务表repository.save(financialModel);

            FinModel.set是否红冲("1");
            FinModel.set修改时间(ts);
            FinModel.set修改用户(request.user);
            FinModel.set操作日期(time);
            销售财务账目表repository.save(FinModel);

            model.set关联编号(FinModel.get账目编号());
            model.set财务编号(FinModel.get财务编号());
            model.set订单编号(FinModel.get订单编号());
            model.set账目日期(new Date(System.currentTimeMillis()));  // 取当天日期
            model.set账目金额(FinModel.get账目金额().negate());
            model.set交易凭证号(FinModel.get交易凭证号());
            model.set创建用户(request.user);
            model.set创建时间(ts);
            model.set修改用户(request.user);
            model.set修改时间(ts);
            model.set删除状态("0");
            model.set是否红冲("0"); // 是否红冲为否
            model.set操作日期(time);
            销售财务账目表repository.save(model);

            result.setResult("true");
            result.setMessage("单据红冲确认保存成功");
            return result;
        } else {
            String message = String.format("找不到财务账目信息。初始报价单号=%s", request.initNum);
            logger.error(message, request.initNum);

            return new ResultData("false",message,null);
        }
    }

    @Override
    public void exportFinanceRedPush(String permit, HttpServletResponse response, Map map, RequestBase request) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            String[] columns = map.get("columns").toString().split("[|]");
            map.remove("columns");
            context.setTemplate("templates/财务单据红冲导出模板.xlsx")
                    .setFileName("财务单据红冲导出模板.xlsx")
                    .setSource(exportRedPushSource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(columns.length)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("param", map)
                    .addParam("columns", columns)
                    .addParam("request", request);

            excelReportService.export(context, response.getOutputStream());
        }catch (Exception e){
            logger.error("财务核销导出模板导出异常", e);
        }
    }
}
